<template>
    <div>
        <div class="e-table" style="background-color: #fff" v-if="showTable">
            <!-- 头部buttons -->
            <div class="top">
                <div class="left">
                    <div v-if="auditState.canModify">
                        <el-button size="small" class="btn-greenYellow" @click="importList"
                        >引入清单</el-button>
                    </div>
                </div>
                 <div class="right">
                    <div>
                        <el-input
                            placeholder="请输入细目编号、细目名称或结构部位进行搜索"
                            size="small"
                            v-model="searchKey"
                            @blur="search"
                        >
                            <i slot="suffix" class="el-input__icon el-icon-search" @click="search"></i>
                        </el-input>
                    </div>
                </div>
            </div>
            <div class="errorMsg" v-if="errorMsg.length>0">
                <span v-for="item,index in errorMsg" :key="index">
                    {{item}}
                </span>
            </div>

            <div class="e-tree-table" v-if="isBidding">
                <el-table v-show="!isSearch" ref="tableRef"
                    :key="tableRef"
                        border
                        style="width: 100%"
                        row-key="billId"
                        :data="tableData"
                        :tree-props="{
                            children: 'children',
                            hasChildren: 'hasChildren'
                        }"
                        :load="onload"
                        lazy
                        :row-class-name="tableRowClassName"
                        class="table"
                    >
                        <el-table-column label="操作" width="200">
                            <template slot-scope="{ row }">
                                <div class="oparation_box">
                                    <i class="el-icon-delete"
                                        style="font-size: 24px; color: #e9513e;"
                                        @click="onDelNode(row)"
                                        v-if="row.isNew && auditState.canModify"
                                        title="删除"
                                    ></i>
                                </div>
                            </template>
                        </el-table-column>
                                            <el-table-column prop="itemNo" label="细目编号" min-width="200" align="left">
                            <template slot-scope="{ row }">
                                <span>{{ row.itemNo }}</span>
                            </template>
                    </el-table-column>
                    <el-table-column prop="itemName" label="细目名称" min-width="200" align="left">
                        <template slot-scope="{ row }">
                            <span>{{ row.itemName }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="structureName" label="结构部位" width="120">
                        <template slot-scope="{ row }">
                            <span>{{ row.structureName }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="unit" label="计量单位" width="120">
                        <template slot-scope="{ row }">
                            <span>{{ row.unit }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="identification" label="标识" width="120">
                        <template slot-scope="{ row }">
                            <span>{{ row.identification }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="unitPriceType" label="单价类型" width="120">
                        <template slot-scope="{ row }">
                            <el-select
                                v-model="row.unitPriceType"
                                placeholder="请选择"
                                    v-if="row.listIsDetailed && auditState.canModify"
                                    @change="unitPriceTypeChange(row)"
                            >
                                <el-option
                                    label="全单价"
                                    :value="1"
                                ></el-option>
                                <el-option
                                    label="劳务单价"
                                    :value="2"
                                ></el-option>
                            </el-select>
                                <div v-else>{{ ['全单价','劳务单价'][row.unitPriceType-1] }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="quantity" label="数量" width="200">
                        <template slot-scope="{ row }">
                            <span>{{ row.quantity }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="unitPrice" label="单价" width="200">
                        <template slot-scope="{ row }">
                            <el-input
                                v-model="row.unitPrice"
                                placeholder="请输入内容"
                                v-if="row.unit !== '总额' && row.itemIsDetailed && !row.structureId && isAdd"
                                @input.native="isNumInput"
                                @change="unitPriceChange(row)"
                            ></el-input>
                            <span v-else-if="row.unit === '总额'">--</span>
                            <span v-else>{{ row.unitPrice }}</span>
                            <historyUpdateTable
                                v-if="row.priceUpdateCount === 1"
                                @clickIcon="clickIcon(row.billId,2)"
                                :historyTable="historyTableData"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column prop="amount" label="金额(元)" width="120">
                        <template slot-scope="{ row }">
                            <el-input
                                v-model="row.amount"
                                placeholder="请输入内容"
                                v-if="row.structureId && mapTableData[row.parentId].unit ==='总额' && isAdd"
                                @change="changeAmount(row)"
                                @input.native="isNumInput"
                            ></el-input>
                            <span v-else>{{ row.amount }}</span>
                            <historyUpdateTable
                            v-if="row.amountUpdateCount === 1"
                                @clickIcon="clickIcon(row.billId,3)"
                                :historyTable="historyTableData"
                            />
                        </template>
                    </el-table-column>
                </el-table>

                <el-table v-if="isSearch" ref="tableRef1"
                    :key="tableRef1"
                    border
                    style="width: 100%"
                    row-key="billId"
                    :data="searchData"
                    :tree-props="{
                        children: 'children',
                        hasChildren: 'hasChildren'
                    }"
                    :load="onload"
                    lazy
                    :row-class-name="tableRowClassName"
                    class="table"
                >
                    <el-table-column  label="操作" width="200">
                    </el-table-column>
                    <el-table-column prop="itemNo" label="细目编号" min-width="200" align="left">
                            <template slot-scope="{ row }">
                                <span>{{ row.itemNo }}</span>
                            </template>
                    </el-table-column>
                    <el-table-column prop="itemName" label="细目名称" min-width="200" align="left">
                        <template slot-scope="{ row }">
                            <span>{{ row.itemName }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="structureName" label="结构部位" width="120">
                        <template slot-scope="{ row }">
                            <span>{{ row.structureName }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="unit" label="计量单位" width="120">
                        <template slot-scope="{ row }">
                            <span>{{ row.unit }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="identification" label="标识" width="120">
                        <template slot-scope="{ row }">
                            <span>{{ row.identification }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="unitPriceType" label="单价类型" width="120">
                        <template slot-scope="{ row }">
                            <el-select
                                v-model="row.unitPriceType"
                                placeholder="请选择"
                                    v-if="row.listIsDetailed && auditState.canModify"
                                    @change="unitPriceTypeChange(row)"
                            >
                                <el-option
                                    label="全单价"
                                    :value="1"
                                ></el-option>
                                <el-option
                                    label="劳务单价"
                                    :value="2"
                                ></el-option>
                            </el-select>
                                <div v-else>{{ ['全单价','劳务单价'][row.unitPriceType-1] }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="quantity" label="数量" width="200">
                        <template slot-scope="{ row }">
                            <span>{{ row.quantity }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="unitPrice" label="单价" width="200">
                        <template slot-scope="{ row }">
                            <el-input
                                v-model="row.unitPrice"
                                placeholder="请输入内容"
                                v-if="row.unit !== '总额' && row.itemIsDetailed && !row.structureId && isAdd"
                                @input.native="isNumInput"
                                @change="unitPriceChange(row)"
                            ></el-input>
                            <span v-else-if="row.unit === '总额'">--</span>
                            <span v-else>{{ row.unitPrice }}</span>
                            <historyUpdateTable
                                v-if="row.priceUpdateCount === 1"
                                @clickIcon="clickIcon(row.billId,2)"
                                :historyTable="historyTableData"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column prop="amount" label="金额(元)" width="120">
                        <template slot-scope="{ row }">
                            <el-input
                                v-model="row.amount"
                                placeholder="请输入内容"
                                v-if="row.structureId && mapTableData[row.parentId].unit ==='总额' && isAdd"
                                @change="changeAmount(row)"
                                @input.native="isNumInput"
                            ></el-input>
                            <span v-else>{{ row.amount }}</span>
                            <historyUpdateTable
                            v-if="row.amountUpdateCount === 1"
                                @clickIcon="clickIcon(row.billId,3)"
                                :historyTable="historyTableData"
                            />
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="e-tree-table" v-else>
                <el-table v-show="!isSearch" ref="tableRef"
                    :key="tableRef"
                    border
                    style="width: 100%"
                    row-key="billId"
                    :data="tableData"
                    :tree-props="{
                        children: 'children',
                        hasChildren: 'hasChildren'
                    }"
                    :load="onload"
                    lazy
                    :row-class-name="tableRowClassName"
                    class="table"
                >
                    <el-table-column label="操作" width="200" align='left'>
                        <template slot-scope="{ row }">
                            <div class="oparation_box">
                                <img src="@/assets/btn/sub.png" class="add_sub"
                                    @click="addChilden(row)"
                                    v-if="(row.listIsDetailed || row.identification === '项') && auditState.canModify"
                                    title="添加子级"
                                    />
                                <i class="el-icon-delete"
                                    style="font-size: 24px; color: #e9513e;"
                                    v-if="auditState.canModify"
                                    @click="onDelNode(row)"
                                    title="删除"
                                ></i>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="itemNo" label="细目编号" min-width="200" align="left">
                        <template slot-scope="{ row }">
                            <el-input
                                v-model="row.itemNo"
                                placeholder="请输入内容"
                                v-if="row.identification === '项' && !row.structureId && auditState.canModify"
                            ></el-input>
                            <div v-else>{{ row.itemNo }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="itemName" label="细目名称" min-width="200" align="left">
                        <template slot-scope="{ row }">
                            <el-input
                                v-model="row.itemName"
                                placeholder="请输入内容"
                                v-if="row.identification === '项' && !row.structureId && auditState.canModify"
                            ></el-input>
                            <div v-else>{{ row.itemName }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="structureName" label="结构部位" min-width="200" align="left">
                        <template slot-scope="{ row }">
                            <div>{{ row.structureName }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="unit" align="center" label="计量单位" width="120">
                        <template slot-scope="{ row }">
                            <el-select
                                v-model="row.unit"
                                v-if="row.identification === '项' && !row.structureId && auditState.canModify"
                                @change="changeUnit(row)"
                            >
                                <el-option
                                    v-for="item in unitList"
                                    :value="item.label"
                                    :label="item.label"
                                    :key="item.label"
                                >
                                </el-option>
                            </el-select>
                            <div v-else>{{ row.unit }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="identification"  align="center"  label="标识" width="120">
                        <template slot-scope="{ row }">
                            <div v-if="!row.structureId">{{ row.identification }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="unitPriceType"  align="center"  label="单价类型" width="150">
                        <template slot-scope="{ row }">
                            <el-select
                                v-model="row.unitPriceType"
                                placeholder="请选择"
                                    v-if="row.listIsDetailed && auditState.canModify"
                                    @change="unitPriceTypeChange(row)"
                            >
                                <el-option
                                    label="全单价"
                                    :value="1"
                                ></el-option>
                                <el-option
                                    label="劳务单价"
                                    :value="2"
                                ></el-option>
                            </el-select>
                                <div v-else>{{ ['全单价','劳务单价'][row.unitPriceType-1] }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="quantity" label="数量"  align="right"  width="120">
                        <template slot-scope="{ row }">
                            <el-input
                                v-model="row.quantity"
                                placeholder="请输入内容"
                                v-if="row.structureId && mapTableData[row.parentId].unit !=='总额' && isAdd"
                                @input.native="isFourInput"
                                @change="quantityChange(row)"
                            ></el-input>
                            <div v-else>{{ row.quantity }}</div>
                            <historyUpdateTable
                                v-if="row.quantityUpdateCount === 1"
                                @clickIcon="clickIcon(row.billId,1)"
                                :historyTable="historyTableData"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column prop="unitPrice" label="单价" align="right" width="120">
                        <template slot-scope="{ row }">
                            <el-input
                                v-model="row.unitPrice"
                                placeholder="请输入内容"
                                v-if="row.unit !== '总额' && row.itemIsDetailed && !row.structureId && isAdd"
                                @input.native="isNumInput"
                                @change="unitPriceChange(row)"
                            ></el-input>
                            <div v-else-if="row.unit === '总额'">--</div>
                            <div v-else>{{ row.unitPrice }}</div>
                            <historyUpdateTable
                                v-if="row.priceUpdateCount === 1"
                                @clickIcon="clickIcon(row.billId,2)"
                                :historyTable="historyTableData"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column prop="amount" label="金额(元)" align="right" width="120">
                        <template slot-scope="{ row }">
                            <el-input
                                v-model="row.amount"
                                placeholder="请输入内容"
                                v-if="row.structureId && mapTableData[row.parentId].unit ==='总额' && isAdd"
                                @change="changeAmount(row)"
                                @input.native="isNumInput"
                            ></el-input>
                            <div v-else>{{ row.amount }}</div>
                            <historyUpdateTable
                                v-if="row.amountUpdateCount === 1"
                                @clickIcon="clickIcon(row.billId,3)"
                                :historyTable="historyTableData"
                            />
                        </template>
                    </el-table-column>
                </el-table>

                <el-table v-if="isSearch" ref="tableRef1"
                    :key="tableRef1"
                    border
                    style="width: 100%"
                    row-key="billId"
                    :data="searchData"
                    :tree-props="{
                        children: 'children',
                        hasChildren: 'hasChildren'
                    }"
                    :load="onload"
                    lazy
                    :row-class-name="tableRowClassName"
                    class="table"
                >
                    <el-table-column  label="操作" width="200" align="left">
                    </el-table-column>
                    <el-table-column prop="itemNo" label="细目编号" min-width="200" align="left">
                        <template slot-scope="{ row }">
                            <el-input
                                v-model="row.itemNo"
                                placeholder="请输入内容"
                                v-if="row.identification === '项' && !row.structureId && auditState.canModify"
                            ></el-input>
                            <div v-else>{{ row.itemNo }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="itemName" label="细目名称" min-width="200" align="left">
                        <template slot-scope="{ row }">
                            <el-input
                                v-model="row.itemName"
                                placeholder="请输入内容"
                                v-if="row.identification === '项' && !row.structureId && auditState.canModify"
                            ></el-input>
                            <div v-else>{{ row.itemName }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="structureName" label="结构部位" min-width="200" align="left">
                        <template slot-scope="{ row }">
                            <div>{{ row.structureName }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="unit" align="center" label="计量单位" width="120">
                        <template slot-scope="{ row }">
                            <el-select
                                v-model="row.unit"
                                v-if="row.identification === '项' && !row.structureId && auditState.canModify"
                                @change="changeUnit(row)"
                            >
                                <el-option
                                    v-for="item in unitList"
                                    :value="item.label"
                                    :label="item.label"
                                    :key="item.label"
                                >
                                </el-option>
                            </el-select>
                            <div v-else>{{ row.unit }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="identification"  align="center"  label="标识" width="120">
                        <template slot-scope="{ row }">
                            <div v-if="!row.structureId">{{ row.identification }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="unitPriceType"  align="center"  label="单价类型" width="150">
                        <template slot-scope="{ row }">
                            <el-select
                                v-model="row.unitPriceType"
                                placeholder="请选择"
                                    v-if="row.listIsDetailed && auditState.canModify"
                                    @change="unitPriceTypeChange(row)"
                            >
                                <el-option
                                    label="全单价"
                                    :value="1"
                                ></el-option>
                                <el-option
                                    label="劳务单价"
                                    :value="2"
                                ></el-option>
                            </el-select>
                                <div v-else>{{ ['全单价','劳务单价'][row.unitPriceType-1] }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="quantity" label="数量"  align="right"  width="120">
                        <template slot-scope="{ row }">
                            <el-input
                                v-model="row.quantity"
                                placeholder="请输入内容"
                                v-if="row.structureId && mapTableData[row.parentId].unit !=='总额' && isAdd"
                                @input.native="isFourInput"
                                @change="quantityChange(row)"
                            ></el-input>
                            <div v-else>{{ row.quantity }}</div>
                            <historyUpdateTable
                                v-if="row.quantityUpdateCount === 1"
                                @clickIcon="clickIcon(row.billId,1)"
                                :historyTable="historyTableData"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column prop="unitPrice" label="单价" align="right" width="120">
                        <template slot-scope="{ row }">
                            <el-input
                                v-model="row.unitPrice"
                                placeholder="请输入内容"
                                v-if="row.unit !== '总额' && row.itemIsDetailed && !row.structureId && isAdd"
                                @input.native="isNumInput"
                                @change="unitPriceChange(row)"
                            ></el-input>
                            <div v-else-if="row.unit === '总额'">--</div>
                            <div v-else>{{ row.unitPrice }}</div>
                            <historyUpdateTable
                                v-if="row.priceUpdateCount === 1"
                                @clickIcon="clickIcon(row.billId,2)"
                                :historyTable="historyTableData"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column prop="amount" label="金额(元)" align="right" width="120">
                        <template slot-scope="{ row }">
                            <el-input
                                v-model="row.amount"
                                placeholder="请输入内容"
                                v-if="row.structureId && mapTableData[row.parentId].unit ==='总额' && isAdd"
                                @change="changeAmount(row)"
                                @input.native="isNumInput"
                            ></el-input>
                            <div v-else>{{ row.amount }}</div>
                            <historyUpdateTable
                                v-if="row.amountUpdateCount === 1"
                                @clickIcon="clickIcon(row.billId,3)"
                                :historyTable="historyTableData"
                            />
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <div>{{ str }}</div>
    </div>
</template>
<script>
// import tenderRequest from '@/api/tender/tender.js'
import { toLocation, vueDom } from '@/utils/common.js'
import { uidBuilder } from '@/api/base/uid.js'
import { getUnit } from '@/api/subcontractApi/currency.js'
import subcontract from '@/api/subcontractApi/subContractApply.js'
import { isFourInput, isNumInput } from '@/utils/rules.js'
import { selectDataClient, showLoading, hideLoading } from '@/utils/common'
import { mapMutations } from 'vuex'
import historyUpdateTable from '@/pages/subcontract/components/historyUpdateTable.vue'
export default {
    props: {
        billid: {
            type: String,
            default: ''
        },
        contractListTable: { //组件绑定的数据
            type: Array,
            default: function () {
                return []
            }
        },
        errorMsg: { //表格错误提示
            type: Array,
            default: function () {
                return []
            }
        },
        isBidding: { //是否是招标
            type: Boolean,
            default: false
        },
        mainInfo: { //主体信息
            type: Object,
            default: function () {
                return {}
            }
        },
        auditState: { //是否可以编辑
            type: Object,
            default: function () {
                return {
                    canAudit: false,
                    canModify: true,
                    canUndoAudit: false,
                    freeNextUnits: [],
                    isFree: false,
                }
            }
        },
        isAdd: { //是否可以编辑数量单价金额
            default: true
        },
        getTableData: { //获取表格数据接口
            type: Function
        },
        state: { //流程状态
            type: Number
        }
    },
    model: {
        prop: 'contractListTable',
        event: 'change'
    },
    computed: {
        tenderId () {
            return this.$route.query.billid
        }
    },
    components: {
        historyUpdateTable,
    },
    watch: {
        contractListTable: {
            handler (newName) {
                this.tableData = newName
            },
            immediate: false,
            deep: true
        },
        tableData: {
            handler (newName) {
                this.$emit('change', newName)
            },
            immediate: true,
            deep: true
        },
    },
    data () {
        return {
            detailsOfProposedArr: [],
            tableData: [],
            mapTableData: {},
            addList: [], // 缓存新增数据
            unitList: [],
            searchKey: '',
            isSearch: false,
            materialList: [],
            showTable: true,
            historyTableData: {},
        }
    },
    created () {
        this.getData()
    },
    mounted () {
        vueDom(
            // 默认0为选中项
            () => {
                $('.el-tree-node:first')?.addClass('is-current')
            },
            () => {
                return $('.el-tree-node:first')?.attr('class')?.includes('is-current')
            }
        )
        getUnit().then(res=>{
            let arr = res.map(x=>{
                let obj = {
                    value: '',
                    label: '',
                }
                obj.value = x.kvValue
                obj.label = x.kvKey
                return obj
            })
            this.unitList = arr
            console.log('unitList', this.unitList)
        })
    },
    methods: {
        ...mapMutations(
            'contract', ['setMaterialList']
        ),
        ...mapMutations(['setHistoryTableData']),
        // 获取数据
        getData () {
            this.showTable = false
            const params = {
                parentId: '0',
                sourceId: this.billid
            }
            this.getTableData(params).then(res=>{
                res.forEach(item=>{
                    item.hasChildren = item.isDetailed ? false : true
                    item.changeType = 0
                    item.children = []
                    if(this.state === 1) {
                        item.quantityUpdateFlag = false
                        item.unitPriceUpdateFlag = false
                        item.amountUpdateFlag = false
                    }
                })
                this.mapTableData['0'] = {
                    children: res
                }
                this.tableData = res
                this.showTable = true
            })
        },
        // 通过id获取子级数据
        async getById (billId) {
            console.log('billId', billId)
            const params = {
                parentId: billId,
                sourceId: this.billid
            }
            let result = await this.getTableData(params)
            result.forEach(item=>{
                item.hasChildren = item.isDetailed ? false : true
                item.children = []
                item.changeType = 0
                if(this.state === 1) {
                    item.quantityUpdateFlag = false
                    item.unitPriceUpdateFlag = false
                    item.amountUpdateFlag = false
                }
            })
            return result
        },
        importList () {
            if(this.isSearch) return
            this.showClient()
        },
        async showClient () {

            if (!this.mainInfo.secondParty.name) {
                this.clientPop('info', '请选择主体信息的乙方名称')
                return
            }
            if (this.mainInfo.secondParty.biddingId) {
                // let list = []
                // showLoading()
                // let listAll = await subcontract.contractListAll({ sourceId: this.billid })//获取所有数据
                // let newListAll = []
                // const treeChangeList = data=>{
                //     data.forEach(item=>{
                //         if(item.children.length > 0) {
                //             treeChangeList(item.children)
                //         }
                //         newListAll.push(item)
                //     })
                // }
                // treeChangeList(this.tableData)//将表格数据展平
                // newListAll = newListAll.filter(x=>x.changeType === -1 && x.oriBillId)
                // newListAll.forEach(item=>{
                //     let index = listAll.findIndex(x=>x.billId === item.billId)
                //     if(index !== -1) {
                //         listAll.splice(index, 1)
                //     }
                // })//过滤已删除的源单并且删掉
                // if(listAll.length > 0) {
                //     listAll.forEach(item=>{
                //         let obj = {
                //             'billId': item.oriBillId,
                //             'isLeaf': item.oriIsDetailed,
                //             'isListLeaf': item.listIsDetailed,
                //             'label': item.identification,
                //             'parentId': item.oriParentBillId,
                //             'subitemId': item.structureId,
                //             'subitemName': item.structureName,
                //         }
                //         list.push(obj)

                //     })
                // }
                // console.log('list', JSON.stringify( list))
                // hideLoading()
                let val = [{ 'amount': 123, 'billId': '1503184517657718785', 'budgetId': '123', 'budgetName': '123', 'changeState': 0, 'code': '123', 'codeName': '123', 'isLeaf': 0, 'isListLeaf': 1, 'label': '0', 'listId': '1503184630874566657', 'num': 123, 'packageId': '1503184623618420737', 'parentId': '0', 'price': 123, 'priceType': '123', 'recordId': '1503184632430653441', 'subitemId': '123', 'subitemName': '123', 'unit': '123' }]
                let arr = []
                const fn = (data, parentId)=>{
                    let arr = val.filter(x=>x.parentId === parentId)
                    let arr1 = arr.map(x=>x.itemNo)
                    arr1 = arr1.sort()
                    arr1.forEach(item=>{
                        data.push( arr.find(x=>x.itemNo === item) )
                    })
                    if(data.length > 0) {
                        data.forEach(item=>{
                            if(item.termIsDetailed === false) {
                                item.children = []
                            }else{
                                item.children = []
                                fn(item.children, item.billId)
                            }

                        })
                    }
                }
                fn(arr, '0')
                this.handleContractListBidding(arr)
                // selectDataClient({
                //     SelectServiceToken: '/tender/apply/inventory/contract/listByPackageId', // 客户端对应方法名
                //     IsSingleMode: false, // 是否单选 true 单选 false 多选
                //     SelectedIDs: [], // 已选中id
                //     InitParamsStr: JSON.stringify({
                //         'keyword': '',
                //         'packageId': this.mainInfo.secondParty.dtlId,
                //         'parenId': '0'
                //     }),
                //     Title: '选择清单' // 标题
                // }).then(val=>{
                //     let arr = []
                //     const fn = (data, parentId)=>{
                //         let arr = val.filter(x=>x.parentId === parentId)
                //         let arr1 = arr.map(x=>x.itemNo)
                //         arr1 = arr1.sort()
                //         arr1.forEach(item=>{
                //             data.push( arr.find(x=>x.itemNo === item) )
                //         })
                //         if(data.length > 0) {
                //             data.forEach(item=>{
                //                 if(item.termIsDetailed === false) {
                //                     item.children = []
                //                 }else{
                //                     item.children = []
                //                     fn(item.children, item.billId)
                //                 }

                //             })
                //         }
                //     }
                //     fn(arr, '0')
                //     this.handleContractListBidding(arr)
                // })
            } else {
                let list = []
                showLoading()
                let listAll = await subcontract.contractListAll({ sourceId: this.billid })//获取所有数据
                let newListAll = []
                const treeChangeList = data=>{
                    data.forEach(item=>{
                        if(item.children.length > 0) {
                            treeChangeList(item.children)
                        }
                        newListAll.push(item)
                    })
                }
                treeChangeList(this.tableData)//将表格数据展平
                newListAll = newListAll.filter(x=>x.changeType === -1 && x.oriBillId)
                newListAll.forEach(item=>{
                    let index = listAll.findIndex(x=>x.billId === item.billId)
                    if(index !== -1) {
                        listAll.splice(index, 1)
                    }
                })//过滤已删除的源单并且删掉
                let structureIdArr = listAll.filter(x=>x.structureId)
                console.log('structureIdArr', structureIdArr)
                if(listAll.length > 0) {
                    listAll.forEach(item=>{
                        if(item.oriBillId && !item.structureId) {
                            let obj = {
                                'identification': item.identification,
                                'isDetailed': item.oriIsDetailed, //原清单的最明细
                                'itemName': item.itemName,
                                'itemNo': item.itemNo,
                                'quantity': item.quantity,
                                'unit': item.unit,
                                'structureId': item.structureId,
                                'structureName': item.structureName,
                                'billId': item.oriBillId,
                                'termIsDetailed': item.listIsDetailed ? 1 : 0,
                                'parentId': item.oriParentBillId,
                            }
                            let arr = structureIdArr.filter(x=>x.oriBillId === obj.billId)
                            if(arr) {
                                obj.structureId = arr.map(x=>x.structureId).join(',')
                                obj.structureName = arr.map(x=>x.structureName).join(',')
                                obj.quantity = arr.map(x=>x.quantity).join(',')
                            }
                            list.push(obj)
                        }

                    })
                }
                console.log('list', JSON.stringify( list))
                hideLoading()
                selectDataClient({
                    SelectServiceToken: 'EngineerSelectorImportDetail', // 客户端对应方法名
                    IsSingleMode: false, // 是否单选 true 单选 false 多选
                    SelectedIDs: [], // 已选中id
                    InitParamsStr: JSON.stringify(list),
                    Title: '选择清单' // 标题
                }).then(val => {
                    alert(JSON.stringify(val))
                    this.str = JSON.stringify(val)
                    let arr = []
                    const fn = (data, parentId)=>{
                        let arr = val.filter(x=>x.parentId === parentId)
                        let arr1 = arr.map(x=>x.itemNo)
                        arr1 = arr1.sort()
                        arr1.forEach(item=>{
                            data.push( arr.find(x=>x.itemNo === item) )
                        })
                        if(data.length > 0) {
                            data.forEach(item=>{
                                if(item.isLeaf === false) {
                                    item.children = []
                                }else{
                                    item.children = []
                                    fn(item.children, item.billId)
                                }

                            })
                        }
                    }
                    fn(arr, '0')
                    this.handleContractList(arr)
                })
                let val = [{ 'billId': '1496032333264850947', 'identification': '清单', 'termIsDetailed': 0, 'isDetailed': false, 'itemName': '总则', 'itemNo': '100章', 'parentId': '0', 'quantity': null, 'unit': null, 'structureId': '1496032333264850951', 'structureName': '盐坪坝大桥基础及下部构2573' }, { 'billId': '1496032333264850949', 'identification': '清单', 'termIsDetailed': 0, 'isDetailed': false, 'itemName': '基础钢筋', 'itemNo': '100-1', 'parentId': '1496032333264850947', 'quantity': null, 'unit': null, 'structureId': '1496032333264850951', 'structureName': '盐坪坝大桥基础及下部构2573' }, { 'billId': '1496032333264850948', 'identification': '清单', 'termIsDetailed': 1, 'isDetailed': true, 'itemName': 'HPB300', 'itemNo': '100-1-a', 'parentId': '1496032333264850949', 'quantity': '10', 'unit': null, 'structureId': '1496032333264850951', 'structureName': '盐坪坝大桥基础及下部构2573' }, { 'billId': '1496032333264850955', 'identification': '清单', 'termIsDetailed': 1, 'isDetailed': true, 'itemName': 'HPB300', 'itemNo': '100-1-b', 'parentId': '1496032333264850949', 'quantity': '10', 'unit': null, 'structureId': '1496032333264850951', 'structureName': '盐坪坝大桥基础及下部构2573' }, { 'billId': '1496443345113714693', 'identification': '清单', 'termIsDetailed': 0, 'isDetailed': false, 'itemName': '基础钢筋1', 'itemNo': '100-2', 'parentId': '1496032333264850947', 'quantity': null, 'unit': null, 'structureId': '1496032333264850951', 'structureName': '盐坪坝大桥基础及下部构2573' }, { 'billId': '1496443345113714694', 'identification': '清单', 'termIsDetailed': 1, 'isDetailed': true, 'itemName': 'HPB300', 'itemNo': '100-2-a', 'parentId': '1496443345113714693', 'quantity': '20', 'unit': null, 'structureId': '1496032333264850951,1500738060493189128', 'structureName': '盐坪坝大桥基础及下部构2573,盐坪坝大桥基础及下部构造5345' }]
                let arr = []
                const fn = (data, parentId)=>{
                    let arr = val.filter(x=>x.parentId === parentId)
                    let arr1 = arr.map(x=>x.itemNo)
                    arr1 = arr1.sort()
                    arr1.forEach(item=>{
                        data.push( arr.find(x=>x.itemNo === item) )
                    })
                    if(data.length > 0) {
                        data.forEach(item=>{
                            if(item.termIsDetailed === false) {
                                item.children = []
                            }else{
                                item.children = []
                                fn(item.children, item.billId)
                            }

                        })
                    }
                }
                fn(arr, '0')
                console.log('arr', arr)
                this.handleContractList(arr)
            }
        },
        //引入目标预算清单
        async handleContractList  (arr) {

            const fn =  (newData, oldData, parentId)=>{
                newData.forEach(async x=>{
                    const resul1 = oldData.find(item=>item.oriBillId === x.billId)
                    if(!resul1) {
                        const uid = await this.uidBuilder({ num: 1 })
                        let obj = {
                            'amount': '',
                            'billId': '',
                            'changeType': 1,
                            'children': [],
                            'itemNo': x.itemNo,
                            'identification': x.identification,
                            'itemName': x.itemName,
                            'quantity': '',
                            'sourceId': this.billid,
                            'structuralPosition': '',
                            'unit': x.unit,
                            'unitPrice': '',
                            'unitPriceType': '',
                            'structureId': '',
                            'structureName': '',
                            'isDetailed': false, //是否最明细
                            'oriBillId': x.billId,
                            'oriParentBillId': x.parentId,
                            'itemIsDetailed': x.isDetailed, //细目最明细
                            'listIsDetailed': x.termIsDetailed//清单最明细
                        }
                        obj.parentId = parentId
                        obj.billId = uid //本级ID
                        obj.oriIsDetailed = x.isDetailed//原清单是否最明细
                        obj.hasChildren = true
                        obj.isNew = true
                        if(!x.isDetailed ) {
                            fn(x.children, obj.children, obj.billId)
                        }
                        if(x.isDetailed) {
                            const structureId = x.structureId.split(',')
                            const structureName = x.structureName.split(',')
                            const quantity = x.quantity.split(',')
                            structureId.forEach(async (item, index)=>{
                                const uid = await this.uidBuilder({ num: 1 })
                                let obj1 = {
                                    'amount': '',
                                    'billId': uid,
                                    'changeType': 1,
                                    'children': [],
                                    'itemNo': '',
                                    'identification': x.identification,
                                    'itemName': '',
                                    'quantity': quantity[index],
                                    'sourceId': this.billid,
                                    'structuralPosition': '',
                                    'unit': '',
                                    'unitPrice': '',
                                    'unitPriceType': '',
                                    'structureId': item,
                                    'structureName': structureName[index],
                                    'isDetailed': true, //是否最明细
                                    'oriBillId': x.billId,
                                    'oriParentBillId': x.parentId,
                                    'itemIsDetailed': false, //细目最明细
                                    'listIsDetailed': false, //清单最明细
                                    'oriIsDetailed': null,
                                    hasChildren: false
                                }
                                obj1.parentId = obj.billId
                                obj1.isNew = true
                                this.mapTableData[obj1.billId] = obj1
                                this.onCalcAmount(obj1)
                                obj.children.push(obj1)

                                this.getmMaterialList(obj1)
                            })
                        }
                        this.mapTableData[obj.billId] = obj
                        oldData.push(obj)
                    }else{
                        if(!x.isDetailed ) {
                            fn(x.children, resul1.children)
                        }
                    }

                })
            }

            fn(arr, this.tableData, '0')
        },
        //引入招标清单
        async handleContractListBidding  (arr) {
            const fn =  (newData, oldData, parentId)=>{
                newData.forEach(async x=>{
                    const resul1 = oldData.find(item=>item.oriBillId === x.billId)
                    if(!resul1) {
                        const uid = await this.uidBuilder({ num: 1 })
                        let obj
                        if(x.subitemId) {
                            obj = {
                                'amount': x.amount,
                                'billId': '',
                                'changeType': 1,
                                'children': [],
                                'itemNo': '',
                                'identification': x.identification,
                                'itemName': '',
                                'quantity': x.unit !== '总额' ? x.num : 0,
                                'sourceId': this.billid,
                                'structuralPosition': '',
                                'unit': x.unit,
                                'unitPrice': x.unit !== '总额' ? x.pricex : 0,
                                'unitPriceType': x.priceType === '劳务单价' ? 2 : 1,
                                'structureId': x.subitemId,
                                'structureName': x.subitemName,
                                'isDetailed': true, //是否最明细
                                'oriBillId': x.billId,
                                'oriParentBillId': x.parentId,
                                'itemIsDetailed': null, //细目最明细
                                'listIsDetailed': null, //清单最明细
                                hasChildren: false
                            }
                            this.mapTableData[parentId].itemIsDetailed = true
                        }else{
                            obj = {
                                'amount': x.amount,
                                'billId': '',
                                'changeType': 1,
                                'children': [],
                                'itemNo': x.code,
                                'identification': x.identification,
                                'itemName': x.codeName,
                                'quantity': x.unit !== '总额' ? x.num : 0,
                                'sourceId': this.billid,
                                'structuralPosition': '',
                                'unit': x.unit,
                                'unitPrice': x.unit !== '总额' ? x.pricex : 0,
                                'unitPriceType': x.priceType === '劳务单价' ? 2 : 1,
                                'structureId': '',
                                'structureName': '',
                                'isDetailed': x.isLeaf, //是否最明细
                                'oriBillId': x.billId,
                                'oriParentBillId': x.parentId,
                                'itemIsDetailed': false, //细目最明细
                                'listIsDetailed': x.isListLeaf, //清单最明细
                                hasChildren: true,
                            }
                        }

                        obj.parentId = parentId
                        obj.billId = uid //本级ID
                        obj.oriIsDetailed = x.isLeaf//原清单是否最明细
                        obj.isNew = true
                        this.mapTableData[obj.billId] = obj
                        oldData.push(obj)
                    }else{
                        if(!x.isDetailed ) {
                            fn(x.children, resul1.children)
                        }
                    }

                })
            }

            fn(arr, this.tableData, '0')
            setTimeout(()=>{
                console.log('tableData', this.tableData)
            }, 3000)
        },
        //计算物资清单
        getmMaterialList (row, operation) {
            const material = {
                billId: row.billId,
                structureId: row.structureId,
                structureName: row.structureName,
                changeType: row.changeType,
                amount: row.amount ? row.amount : 0,
                num: row.quantity ? row.quantity : 0,
                type: row.identification === '清单' ? 1 : 2
            }
            if(operation === 'delete' && material.changeType === 1) {
                material.num = 0
                material.amount = 0
            }
            let index  = this.materialList.findIndex(x=>x.billId === material.billId)
            if(index !== -1) {
                this.materialList[index] = material
            }else{
                this.materialList.push(material)
            }
            if((operation === 'delete' && material.changeType === -1) || (operation !== 'delete' &&  material.changeType !== -1)) {
                const params = {
                    infos: this.materialList,
                    sourceId: this.billid
                }
                subcontract.getListProportion(params).then(res=>{
                    res.map(item=>{
                        item.structureName = material.structureName
                        return item
                    })
                    this.setMaterialList(res)
                })
            }

        },
        async onload (row, treeNode, resolve) {
            let result
            if(row.children.length > 0) {
                result = row.children
            }else{
                // 如果不是最子级，就从接口取
                if (!row.isDetailed) {
                    result = await this.getById(row.billId)
                } else {
                // 是最子级，则初始为空，合并新增数据，并设为非最子级
                    result = []
                    row.isDetailed = false
                }
                // 如果有缓存数据，说明是点击的 “添加子级” 按钮
                if (this.addList.length > 0) {
                    result = result.concat(this.addList)
                    this.addList = []
                }
            }
            row.treeNode = treeNode
            row.resolve = resolve
            row.children = result
            this.mapTableData[row.billId] = row
            resolve(result)
        },
        // 添加子级
        async addChilden (row) {
            const { billId } = row
            const uid = await this.uidBuilder({ num: 1 })
            console.log('row', row)

            let addData = {
                'amount': '',
                'changeType': 1,
                'children': [],
                'itemNo': '',
                'identification': '项',
                'itemName': '',
                'quantity': '',
                'sourceId': this.billid,
                'structuralPosition': '',
                'unit': '',
                'unitPrice': '',
                'unitPriceType': row.unitPriceType,
                'structureId': '',
                'structureName': '',
                'oriIsDetailed': null,
                'oriBillId': '',
                listIsDetailed: false,
                parentId: billId, //父级ID
                billId: uid, //本级ID
                isDetailed: true,
                hasChildren: false,
                isNew: true
            }
            addData.itemIsDetailed = true//是否是明细最子级
            /*
                如果是清单最子级新增，下面没有项则新增一项，结构部位下移到项，如果有项，则新增一项，将其他最子级项的结构部位复制到新增项里面
                如果是项新增子级，则在改项下新增一级项，把结构部位下移到新增项下面
            */
            const getChildren = ()=>{
                return new Promise(resolve=>{
                    let children = []
                    const fn  = async data=>{
                        if(data[0].isDetailed) {
                            const index = data.length
                            data.forEach(async (x, i)=>{
                                let obj = {
                                    'amount': '',
                                    'changeType': x.changeType,
                                    'children': [],
                                    'itemNo': '',
                                    'identification': '项',
                                    'itemName': '',
                                    'quantity': '',
                                    'sourceId': this.billid,
                                    'stt': '',
                                    'unitPrice': '',
                                    'unitPriceType': '',
                                    'structureId': x.structureId,
                                    'structureName': x.structureName,
                                    'oriIsDetailed': null,
                                    'oriBillId': '',
                                    listIsDetailed: false,
                                    parentId: '', //父级ID
                                    billId: x.billId, //本级ID
                                    isDetailed: true,
                                    hasChildren: false,
                                    isNew: true
                                }
                                addData.isDetailed = false
                                addData.hasChildren = true
                                children.push(obj)
                                if(i === index - 1) {
                                    resolve(children)
                                }
                            })
                        }else{
                            if(data[0].children.length > 0) {
                                fn(data[0].children)
                            }else{
                                const params = {
                                    parentId: data[0].billId,
                                    sourceId: this.billid
                                }
                                let result = await subcontract.getContractList(params)
                                fn(result)
                            }
                        }
                    }
                    if(!row.isDetailed) { //如果不是最明细就往下找
                        if(row.children.length > 0) {
                            fn(row.children)
                        }else{
                            const params = {
                                parentId: row.billId,
                                sourceId: this.billid
                            }
                            subcontract.getContractList(params).then(result=>{
                                fn(result)
                            })
                        }
                    }
                })
            }
            row.itemIsDetailed = false
            getChildren().then(children=>{
                new Promise(resolve=>{
                    if(row.children[0].isDetailed) {
                        row.children.splice(0)
                        children.forEach(item=>{
                            item.parentId = addData.billId
                            if(item.changeType === 0) {
                                item.changeType = 2
                            }
                            this.getmMaterialList(item)
                        })
                        resolve(children)
                    }else{
                        this.uidBuilder({ num: children.length }).then(uids=>{
                            uids = uids.split(',')
                            children.forEach((item, index)=>{
                                item.parentId = addData.billId
                                item.billId = uids[index]
                                item.changeType = 1
                                this.getmMaterialList(item)
                            })
                            resolve(children)
                        })
                    }
                }).then(children=>{
                    console.log('children', children)
                    addData.children = children ? children : []
                    this.mapTableData[addData.billId] = addData
                    const tableRef = this.$refs.tableRef
                    if (!this.mapTableData[billId]) {
                        // 缓存新增数据
                        this.addList.push(addData)
                        // 如果是最子级，则设为目录
                        if (!row.hasChildren) {
                            row.children = row.children ? row.children : []
                            row.children = row.children.length > 0 ? row.children.push(addData) : [addData]
                            row.hasChildren = true
                            row.isDetailed = false
                            console.log('row', { ...row })
                            this.mapTableData[billId] = row
                            this.onCalcAmount(addData)
                            // 切换展开状态
                            this.$nextTick(() => {
                                // tableRef.toggleRowExpansion(row, true)
                                tableRef.store.loadOrToggle(row)
                            })
                        // }
                        } else {
                            // 展开子级
                            // tableRef.store.loadData(row, billId)
                            tableRef.store.loadOrToggle(row)
                        }
                    } else {
                        // 已经展开，则直接添加
                        row.children.push(addData)
                        row.hasChildren = true
                        row.isDetailed = false
                    }
                    // 定位到新添加行
                    toLocation(addData)
                })

            })
        },
        onDelNode (row) {
            const deleteFn = row=>{
                const deleteStru = row=>{//删除结构部位
                    const siblings = this.mapTableData[row.parentId].children
                    const index = siblings.findIndex(x=>x.billId === row.billId)
                    if(siblings[index].changeType === 1) {
                        this.getmMaterialList({ ...siblings[index] }, 'delete')
                        siblings.splice(index, 1)
                    }else{
                        siblings[index].changeType = -1
                        this.getmMaterialList({ ...siblings[index] })
                    }
                    this.onCalcAmount(row)
                }

                const fn1 = data=>{ //向下删除
                    if(data.children.length > 0) {
                        for(let i = 0;i < data.children.length;i++)
                        {
                            fn1(data.children[i])
                            if(data.children[i].changeType === 1) {
                                data.children.splice(i, 1)
                                i--
                            }else{
                                data.children[i].changeType = -1
                            }
                            this.onCalcAmount(data.children[i])
                        }
                    }else{
                        deleteStru(data)
                    }
                }
                fn1(row)
                const fn = data=>{ //向上删除
                    if(data.parentId !== '0') {
                        const siblings = this.mapTableData[data.parentId].children
                        const index = siblings.findIndex(x=>x.billId === data.billId)
                        const filterSibings = siblings.filter(x=>x.changeType !== -1)
                        if(filterSibings.length > 1) {
                            if(siblings[index].changeType === 1) {
                                siblings.splice(index, 1)
                            }else{
                                siblings[index].changeType = -1
                            }
                            this.onCalcAmount(siblings[index])
                        }else{
                            fn(this.mapTableData[data.parentId])
                            if(siblings[index].changeType === 1) {
                                siblings.splice(index, 1)
                            }else{
                                siblings[index].changeType = -1
                            }
                        }
                    }else{
                        console.log('tableData', this.tableData)
                        const index = this.tableData.findIndex(x=>x.billId === data.billId)

                        if(this.tableData[index].changeType === 1) {
                            this.tableData.splice(index, 1)
                        }
                        else{
                            this.tableData[index].changeType = -1
                        }
                        this.mapTableData['0'].children = this.tableData
                    }
                }
                fn(row)
            }
            // 如果是新增的，则直接删除
            if (row.changeType === 1) {
                deleteFn(row)
            } else {
                // 否则先提示，再删除
                this.clientPop('err', this.oneDeleteErr, () => {
                    deleteFn(row)
                })
            }
        },
        // 输入后计划金额
        onCalcAmount (row) {
            this.$emit('isMonitorTaxRate')
            if(row.structureId && this.mapTableData[row.parentId].unit === '总额') {
                console.log('')
            }else{
                row.amount = row.changeType !== -1 ?  row.quantity * row.unitPrice : 0
            }

            if(row.changeType !== -1) {
                row.changeType = row.changeType === 1   ? 1 : 2
            }
            if(row.structureId) {
                this.getmMaterialList(row)
            }
            // 向上汇总金额
            this.recurCount({
                parentId: row.parentId,
                rootId: '0',
                listField: 'billId',
                parentField: 'parentId',
                row
            })
        },
        // 递归统计父级
        recurCount ({ parentId, rootId, listField, parentField, row }) {
            // 到根节点
            if (parentId === rootId) {
                return
            }
            const parent = this.mapTableData[parentId]
            // 统计所有同级
            let countSibling = parent.children.reduce((prev, item) => {
                item.amount = item.amount ? parseFloat(item.amount) : item.amount
                return prev + (item.changeType !== -1 ? item.amount : 0)
            }, 0)
            // 赋值汇总数据给父级
            countSibling = typeof (countSibling) === 'string' ? parseFloat(countSibling) : countSibling
            parent.amount = parseFloat(countSibling.toFixed(2))
            if(parent.changeType !== -1) {
                parent.changeType = parent.changeType === 1 ? 1 : 2
            }
            // 未到根节点则继续遍历父节点
            return this.recurCount({
                parentId: parent[parentField],
                rootId,
                listField,
                parentField,
                row,
            })
        },
        tableRowClassName ({ row }) {
            if(row.changeType === -1) {
                if(row.hasChildren) {
                    return `class-${row.billId} row-hide`
                }else{
                    return `class-${row.billId}  row-hide hide-icon`
                }
            }else{
                if(row.hasChildren) {
                    return `class-${row.billId} row-show`
                }else{
                    return `class-${row.billId}  row-show hide-icon`
                }
            }
        },

        async uidBuilder (params) {
            let temp = ''
            await uidBuilder(params).then(res => {
                temp = res.length === 1 ? res[0] : res
            })
            return temp
        },
        // refreshLoadTree (parentId) {
        //     // 根据父级id取出对应节点数据
        //     // const { row, treeNode, resolve } = this.mapTableData[parentId]
        //     let children = this.mapTableData[parentId].children
        //     const tableRef = this.$refs.tableRef
        //     this.$set(tableRef.store.states.lazyTreeNodeMap, parentId, children)
        // },

        isFourInput (event) {
            isFourInput(event)
        },
        isNumInput (event) {
            isNumInput(event)
        },
        search () {
            this.isSearch = false
            this.searchData = []
            this.$emit('isSearch', this.isSearch)
            if(this.searchKey.length > 0) {
                this.searchData = []
                subcontract.searchContractList({
                    key: this.searchKey,
                    sourceId: this.billid
                }).then(res=>{
                    this.isSearch = true
                    //平级列表转成树形结构
                    let arr = []
                    const fn = (data, parentId)=>{
                        let arr = res.filter(x=>x.parentId === parentId)
                        let arr1 = arr.map(x=>x.itemNo)
                        arr1 = arr1.sort()
                        arr1.forEach(item=>{
                            data.push( arr.find(x=>x.itemNo === item) )
                        })
                        if(data.length > 0) {
                            data.forEach(item=>{
                                item.hasChildren = !item.isDetailed
                                item.changeType = 0
                                if(item.isDetailed) {
                                    item.children = []
                                }else{
                                    item.children = []
                                    fn(item.children, item.billId)
                                }

                            })
                        }
                    }
                    fn(arr, '0')
                    this.searchData = arr
                    this.$emit('isSearch', this.isSearch, this.searchData)
                })
            }
        },
        //单价类型切换
        unitPriceTypeChange (row) {
            const fn = async data=>{
                if(!data.isDetailed) {
                    if(data.children.length > 0) {
                        data.children.forEach(item=>{
                            item.unitPriceType = data.unitPriceType
                            if(!item.isDetailed) {
                                fn(item)
                            }
                            this.editChangeType(item)
                            this.mapTableData[data.billId] = data
                        })
                    }else{
                        const params = {
                            parentId: data.billId,
                            sourceId: this.billid
                        }
                        let result = await subcontract.getContractList(params)
                        data.children = result.map(x=>{
                            x.changeType = 0
                            x.hasChildren = !x.isDetailed
                            x.children = []
                            return x
                        })
                        fn(data)
                    }
                }else{
                    this.editChangeType(data)
                }

            }
            if(!row.isDetailed) {
                fn(row)
            }else{
                this.mapTableData[row.billId] = row
            }
        },
        //改变当前分支的changeType
        editChangeType (row) {
            if(this.state === 1) {
                row.unitPriceUpdateFlag = true
            }
            const fn = row=>{
                console.log('row', row)
                row.changeType = row.changeType === 1 ? 1 : 2
                if(row.parentId !== '0') {
                    const parent = this.mapTableData[row.parentId]
                    fn(parent)
                }
            }
            fn(row)
        },
        //单价切换
        unitPriceChange (row) {
            if(row.children.length > 0) {
                row.children.forEach(item=>{
                    item.unitPrice = row.unitPrice
                    this.mapTableData[item.billid] = item
                    this.onCalcAmount(item)
                })
                this.mapTableData[row.billid] = row
            }else{
                this.onCalcAmount(row)
            }
        },
        //数量切换
        quantityChange (row) {
            if(this.state === 1) {
                row.quantityUpdateFlag = true
            }
            const parent = this.mapTableData[row.parentId]
            // 统计所有同级
            const countSibling = parent.children.reduce((prev, item) => {
                return prev + Math.round(item.changeType !== -1 ? item.quantity : 0)
            }, 0)
            // 赋值汇总数据给父级
            parent.quantity = countSibling // 赋值汇总数据给父级
            this.onCalcAmount(row)
        },
        //计量单位切换
        changeUnit (row) {
            console.log('row', row)
            if(row.unit === '总额') {
                row.quantity = 0
                row.unitPrice = 0
                row.children.forEach(item=>{
                    item.quantity = 0
                    item.unitPrice = 0
                    item.amount = 0
                    this.onCalcAmount(item)
                })
            }

        },
        //金额切换
        changeAmount (row) {
            if(this.state === 1) {
                row.amountUpdateFlag = true
            }
            this.onCalcAmount(row)
        },
        clearData () {
            const arr = [ ...this.tableData]
            const deleteFn = row=>{
                const deleteStru = row=>{//删除结构部位
                    const siblings = this.mapTableData[row.parentId].children
                    const index = siblings.findIndex(x=>x.billId === row.billId)
                    if(siblings[index].changeType === 1) {
                        this.getmMaterialList({ ...siblings[index] }, 'delete')
                        siblings.splice(index, 1)
                    }else{
                        siblings[index].changeType = -1
                        this.getmMaterialList({ ...siblings[index] })
                    }
                    this.onCalcAmount(row)
                }

                const fn1 = data=>{ //向下删除
                    if(data.children.length > 0) {
                        for(let i = 0;i < data.children.length;i++)
                        {
                            fn1(data.children[i])
                            if(data.children[i].changeType === 1) {
                                data.children.splice(i, 1)
                                i--
                            }else{
                                data.children[i].changeType = -1
                            }
                            this.onCalcAmount(data.children[i])
                        }
                    }else{
                        deleteStru(data)
                    }
                }
                fn1(row)
                const fn = data=>{ //向上删除
                    if(data.parentId !== '0') {
                        const siblings = this.mapTableData[data.parentId].children
                        const index = siblings.findIndex(x=>x.billId === data.billId)
                        const filterSibings = siblings.filter(x=>x.changeType !== -1)
                        if(filterSibings.length > 1) {
                            if(siblings[index].changeType === 1) {
                                siblings.splice(index, 1)
                            }else{
                                siblings[index].changeType = -1
                            }
                            this.onCalcAmount(siblings[index])
                        }else{
                            fn(this.mapTableData[data.parentId])
                            if(siblings[index].changeType === 1) {
                                siblings.splice(index, 1)
                            }else{
                                siblings[index].changeType = -1
                            }
                        }
                    }else{
                        const index = this.tableData.findIndex(x=>x.billId === data.billId)

                        if(this.tableData[index].changeType === 1) {
                            this.tableData.splice(index, 1)
                        }
                        else{
                            this.tableData[index].changeType = -1
                        }
                        this.mapTableData['0'].children = this.tableData
                    }
                }
                fn(row)
            }
            arr.forEach(item=>{
                deleteFn(item)
            })
        },
        clickIcon (billId, type) {
            this.setHistoryTableData([])
            subcontract.getListUpdateRecord({
                billId,
                type
            }).then(res=>{
                this.setHistoryTableData(res)
            })
        },
    }
}
</script>
<style lang='scss' scoped>
    ::v-deep .hide-icon{
        .el-table__expand-icon{
            display: none;
        }
    }
    .right{
        .el-input {
            width:350px
        }
    }
    ::v-deep.el-table__row{
        .cell{
            display: flex;
        }
        td:nth-child(5),td:nth-child(6),td:nth-child(7){
            .cell{
                display: block;
            }
        }
        td:nth-child(8),td:nth-child(9),td:nth-child(10){
            .cell{
                justify-content: flex-end;
            }
        }
    }
</style>
